package cn.tohsaka.factory.dockercraft.Handlers

import cn.tohsaka.factory.dockercraft.Libraries.ConfigureProvider
import org.webbitserver.HttpControl
import org.webbitserver.HttpHandler
import org.webbitserver.HttpRequest
import org.webbitserver.HttpResponse
import java.io.File
import java.net.URI

/**
 * Created by Xmsoft on 2017/8/9.
 */
class installerHandler:HttpHandler{
    override fun handleHttpRequest(req: HttpRequest, res: HttpResponse, rec: HttpControl) {
        if(req.uri().contains("bash")){
            var bash = File("install/install.sh").readText(Charsets.UTF_8).replace("server_ngx_conf","http://"+getIp()+":"+ConfigureProvider.get("listening")+"/install/ngx_conf");
            res.header("Content-type","text/plain;charset=utf-8");
            res.content(bash).end();
            return;
        }else if(req.uri().contains("ngx_conf")){
            var bash = File("install/sample").readText(Charsets.UTF_8).replace("server_ip",getIp()+":"+ConfigureProvider.get("listening")+"/dockerapi_auth");
            res.header("Content-type","text/plain;charset=utf-8");
            res.content(bash).end();
        }else{
            res.end();
        }
    }
    fun getIp():String{
        var ip=ConfigureProvider.get("ip");
        if(ip==null){
            return URI("http://ip.3322.net/").toURL().openConnection().getInputStream().bufferedReader().readText().trim();
        }else{
            return ip;
        }
    }
}